package com.rocker.graduation.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.rocker.graduation.constants.Constants;
import com.rocker.graduation.dao.CartMapper;
import com.rocker.graduation.dao.CategoryMapper;
import com.rocker.graduation.dao.ConsigneeMapper;
import com.rocker.graduation.dao.InventoryMapper;
import com.rocker.graduation.dao.OrdersMapper;
import com.rocker.graduation.dao.StatusMapper;
import com.rocker.graduation.domain.Consignee;
import com.rocker.graduation.domain.Orders;
import com.rocker.graduation.domain.OrdersExample;
import com.rocker.graduation.domain.Status;
import com.rocker.graduation.domain.StatusExample;
import com.rocker.graduation.entity.CartBean;
import com.rocker.graduation.entity.ConsigneeBean;
import com.rocker.graduation.entity.OrderBean;
import com.rocker.graduation.entity.StatusBean;
import com.rocker.graduation.enums.OrderStatusEnum;
import com.rocker.graduation.exception.RemoteSensingException;
import com.rocker.graduation.service.ICartService;
import com.rocker.graduation.service.IOrderService;

@Service
public class OrderService implements IOrderService {
	@Autowired
	private OrdersMapper ordersMapper;
	
	@Autowired
	private ConsigneeMapper consigneeMapper;
	
	@Autowired
	private ICartService cartService;
	
	@Autowired
	private CartMapper cartMapper;
	
	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private InventoryMapper inventoryMapper;
	
	@Autowired
	private StatusMapper statusMapper;

	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#saveOrder(java.lang.Integer, java.lang.String, java.lang.String)
	 */
	@Override
	@Transactional(rollbackFor={Exception.class})
	public String saveOrder(Integer userId, String payType, String shipType) {
		List<CartBean> cartBeans= cartService.getCartItem(userId);
		if (CollectionUtils.isEmpty(cartBeans)) {
			throw new RemoteSensingException(Constants.ERROR_NULL_CART);
		}
		BigDecimal price = new BigDecimal(0);
		for (CartBean cartBean : cartBeans) {
			price = cartBean.getPrice().add(price);
		}
		BigDecimal ship_fee = new BigDecimal(0);
		switch (shipType) {
		case "ftp":
			ship_fee.add(new BigDecimal(0));
			break;
		case "cd":
			ship_fee.add(new BigDecimal(10));
			break;
		
		default:
			break;
		}
		
		BigDecimal total_price = price.add(ship_fee);
		String inventoryId = cartService.getInventoryId(userId);
		Date now = ordersMapper.getSysDate();
		Orders order = new Orders();
		String orderId = ordersMapper.getOrderId();
		order.setOrderId(orderId);
		order.setPayment(payType);
		order.setInventoryId(inventoryId);
		order.setCategoryPrice(price);
		order.setDiscount("0.00");
		order.setTotalPrice(total_price);
		order.setOrderStatus(1);
		order.setPayment(payType);
		order.setShipping(shipType);
		order.setUserId(userId);
		order.setCreateDate(now);
		order.setShippingFee(ship_fee);
		int i = ordersMapper.insertSelective(order);
		Status status = new Status();
		status.setOrderId(orderId);
		status.setOrderStatus(1);
		status.setModifyDate(now);
		int j = statusMapper.insertSelective(status);
		if (i > 0 && j > 0) {
			cartService.removeCart(userId);
			return orderId;
		}else {
			throw new RemoteSensingException(Constants.ERROR_NULL_CART);
		}
	}
	

	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#listOrders(java.lang.Integer)
	 */
	@Override
	public List<OrderBean> listOrders(Integer userId) {
		List<OrderBean> orderList = new ArrayList<OrderBean>();
		OrdersExample example = new OrdersExample();
		example.createCriteria().andUserIdEqualTo(userId);
		example.setOrderByClause("CREATE_DATE DESC");
		List<Orders> orders = ordersMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(orders)) {
			for (Orders order : orders) {
				OrderBean orderBean = new OrderBean();
				BeanUtils.copyProperties(order, orderBean);
				orderBean.setStatus(OrderStatusEnum.getOrderStatusByKey(
						order.getOrderStatus()).getDesc());
				orderList.add(orderBean);
			}
		}
		
		return orderList;
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#getOrderDetails(java.lang.Integer)
	 */
	@Override
	public void getOrderDetails(Integer orderId){
		
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#cancelOrder(java.lang.String)
	 */
	@Override
	public int cancelOrder(String orderId){
		Date now = ordersMapper.getSysDate();
		Orders orders = new Orders();
		orders.setOrderId(orderId);
		orders.setOrderStatus(0);
		orders.setModifyDate(now);
		Status status = new Status();
		status.setOrderId(orderId);
		status.setOrderStatus(0);
		status.setModifyDate(now);
		int i = ordersMapper.updateByPrimaryKeySelective(orders);
		int j = statusMapper.insertSelective(status);
		return i + j;
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#saveConsignee(java.lang.Integer, int, com.rocker.graduation.entity.ConsigneeBean)
	 */
	@Override
	public boolean saveConsignee(Integer userId, int type, ConsigneeBean consigneeBean){
		Consignee consignee = new Consignee();
		consignee.setAddress(consigneeBean.getAddress());
		consignee.setCity(consigneeBean.getCity());
		consignee.setCountry(consigneeBean.getCountry());
		consignee.setEmail(consigneeBean.getEmail());
		consignee.setName(consigneeBean.getName());
		consignee.setPhoneNumber(consigneeBean.getPhone());
		consignee.setPostCode(consigneeBean.getPostCode());
		consignee.setProvince(consigneeBean.getProvince());
		consignee.setUserId(userId);
		int i = 0;
		if (type == 1) {
			i = consigneeMapper.insertSelective(consignee);
		}else {
			i = consigneeMapper.updateByPrimaryKeySelective(consignee);
		}
		
		return i == 0 ? false : true;
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#getConsignee(java.lang.Integer)
	 */
	@Override
	public ConsigneeBean getConsignee(Integer userId){
		Consignee consignee = consigneeMapper.selectByPrimaryKey(userId);
		ConsigneeBean consigneeBean = new ConsigneeBean();
		if (null == consignee) {
			return null;
		}
		BeanUtils.copyProperties(consignee, consigneeBean);
		consigneeBean.setPhone(consignee.getPhoneNumber().split("-")[1]);
		return consigneeBean;
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#checkConsignee(java.lang.Integer)
	 */
	@Override
	public int checkConsignee(Integer userId){
		return consigneeMapper.selectByPrimaryKey(userId) == null ? 1 : 0;
	}

	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#pay(java.lang.String)
	 */
	@Override
	public boolean pay(String orderId){
		Date now = ordersMapper.getSysDate();
		Orders order = new Orders();
		order.setOrderId(orderId);
		order.setOrderStatus(2);
		order.setModifyDate(now);
		Status status = new Status();
		status.setOrderId(orderId);
		status.setOrderStatus(2);
		status.setModifyDate(now);
		int i = ordersMapper.updateByPrimaryKeySelective(order);
		int j = statusMapper.insertSelective(status);
		return i > 0 && j > 0 ? true : false;
	}
	
	/* (non-Javadoc)
	 * @see com.rocker.graduation.service.impl.IOrderService#getOrderItem(java.lang.String, java.lang.Integer)
	 */
	@Override
	public OrderBean getOrderItem(String orderId, Integer userId){
		OrderBean orderBean = new OrderBean();
		StatusBean statusBean = new StatusBean();
		Orders order = ordersMapper.selectByPrimaryKey(orderId);
		if (null == order) {
			return null;
		}
		StatusExample example = new StatusExample();
		example.createCriteria().andOrderIdEqualTo(orderId);
		List<Status> status = statusMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(status)) {
			orderBean.setStatusDate(statusBean);
		}
		for (Status sta : status) {
			switch (sta.getOrderStatus()) {
			case 1:
				statusBean.setPending(sta.getModifyDate());
				break;
			case 2:
				statusBean.setPayed(sta.getModifyDate());
				break;
			case 3:
				statusBean.setProcessing(sta.getModifyDate());
				break;
			case 4:
				statusBean.setShipped(sta.getModifyDate());
				break;
			case 5:
				statusBean.setCompleted(sta.getModifyDate());
				break;
			case 0:
				statusBean.setCompleted(sta.getModifyDate());
				break;

			default:
				break;
			}
		}
		ConsigneeBean consignee = getConsignee(userId);
		List<CartBean> cartBeans = ordersMapper.getCartItemByInventoryId(order.getInventoryId());
		orderBean.setConsignee(consignee);
		orderBean.setItems(cartBeans);
		orderBean.setStatusDate(statusBean);
		orderBean.setDiscount(new BigDecimal("0.00"));
		BeanUtils.copyProperties(order, orderBean);
		return orderBean;
	}
}
